package com.huifer.wgx.aop;

import com.huifer.wgx.json.JsonUtil;
import com.huifer.wgx.pojo.WebLogInfo;
import com.huifer.wgx.request.RequestUtil;
import io.swagger.annotations.ApiOperation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.logstash.logback.marker.Markers;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * <p>Title : WebLogAspect </p>
 * <p>Description : </p>
 *
 * @author huifer
 * @date 2019-03-18
 */
@Aspect
@Component
@Order(1)
public class WebLogAspect {

    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);
    /**
     * 开始时间
     */
    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution(public * com.huifer.wgx.controller.*.*(..)))")
    public void webLog() {

    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
    }

    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取当前请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        WebLogInfo webLogInfo = new WebLogInfo();

        String doClassName = joinPoint.getTarget().getClass().getName();

        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation log = method.getAnnotation(ApiOperation.class);
            webLogInfo.setDesc(log.value());
        }
        long endTime = System.currentTimeMillis();

        webLogInfo.setBasePath(RequestUtil.getBasePath(request));
        webLogInfo.setIp(request.getRemoteUser());
        webLogInfo.setMethod(request.getMethod());
        webLogInfo.setParameter(doClassName.contains("File")?"文件操作":getParameter(method, joinPoint.getArgs()));
        webLogInfo.setResult(doClassName.contains("File")?"文件操作":result);
        webLogInfo.setSpendTime((int) (endTime - startTime.get()));
        webLogInfo.setStartTime(startTime.get());
        webLogInfo.setUri(request.getRequestURI());
        webLogInfo.setUrl(request.getRequestURL().toString());

        Map<String, Object> logMap = new HashMap<>();
        logMap.put("url", webLogInfo.getUrl());
        logMap.put("method", webLogInfo.getMethod());
        logMap.put("parameter", webLogInfo.getParameter());
        logMap.put("spendTime", webLogInfo.getSpendTime());
        logMap.put("description", webLogInfo.getDesc());
        LOGGER.info(Markers.appendEntries(logMap), JsonUtil.obj2Json(webLogInfo));
        startTime.remove();
        return result;

    }

    /**
     * 获取方法的传入参数，请求参数
     *
     * @param method 方法
     * @param args 参数列表
     * @return 参数列表
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] pms = method.getParameters();
        for (int i = 0; i < pms.length; i++) {
            RequestBody requestBody = pms[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            RequestParam requestParam = pms[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String k = pms[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    k = requestParam.value();
                }
                map.put(k, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }

}
